/**
 * v-drag
 * 移动div
 */
import type { Directive, DirectiveBinding } from 'vue'
const drag: Directive = {
  mounted(el: any, binding: DirectiveBinding) {
    let offsetX = 0
    let offsetY = 0
    let originalPosition = { left: el.offsetLeft, top: el.offsetTop }

    const mouseDownHandler = (e: any) => {
      originalPosition = { left: el.offsetLeft, top: el.offsetTop }
      offsetX = e.clientX - originalPosition.left
      offsetY = e.clientY - originalPosition.top

      document.addEventListener('mousemove', mouseMoveHandler)
      document.addEventListener('mouseup', mouseUpHandler)
    }

    const mouseMoveHandler = (e: any) => {
      el.style.position = 'absolute'
      el.style.left = `${e.clientX - offsetX}px`
      el.style.top = `${e.clientY - offsetY}px`
    }

    const mouseUpHandler = () => {
      // 恢复到原来的位置
      el.style.left = `${originalPosition.left}px`
      el.style.top = `${originalPosition.top}px`

      document.removeEventListener('mousemove', mouseMoveHandler)
      document.removeEventListener('mouseup', mouseUpHandler)
    }

    el.addEventListener('mousedown', mouseDownHandler)
  }
}

export default drag
